const router = require('koa-router')()
const fs = require("fs");
const path = require("path");
const checkToken = require("../static/checkToken");

let selectALL = "select * from users"
let insertSql = "insert into users (user_id, user_name, user_password, user_phone, user_email, user_address, changeTime, user_avatar) values (?, ?, ?, ?, ?, ?, ?, ?)"

const url = path.join(__dirname, "../static/user.json");
let obj = JSON.parse(fs.readFileSync(url).toString());

const produceId = () => { 
  return Math.random().toString(36).substr(3) + Date.now().toString(36);
}

const nowPageList = async (ctx, page) => {
  let result = await ctx.db.EXCUTE(selectALL, []);
  console.log(result)
  if(result.length <= (page - 1) * 10) {
    console.log("此时这个判定执行了");
    return result.slice((page - 2) * 10, (page - 1) * 10)
  }
  console.log(result.slice((page - 1) * 10 , page * 10));
  return result.slice((page - 1) * 10 , page * 10).reverse();
}

const nowLength = async (ctx) => {
  let result = await ctx.db.EXCUTE(selectALL, []);
  return result.length;
}

router.prefix('/users')


// 已修改
router.post("/editData", async (ctx, next) => {
  let checkRes = await checkToken.cheakToken(ctx);
  if(checkRes) {
    let result = await ctx.db.EXCUTE(selectALL, []);
    let data = ctx.request.body;
    for(let item in result) {
      let name = result[item].user_name;
      if(result[item].user_id === ctx.request.body.user_id) {
        result[item].user_name = '';
        if(result.findIndex(item => item.user_name === ctx.request.body.user_name) != -1) {
          result[item].user_name = name;
          ctx.body = {code: "500", msg: "该用户名已存在，请重新输入"}
        } else {
          let sql = "update users set user_name = ?, user_phone = ?, user_email = ?, user_address = ?, changeTime = ? where user_id = ?"
          let result1 = await ctx.db.EXCUTE(sql, [data.user_name, data.user_phone, data.user_email, data.user_address, Date.now(), data.user_id]);
          let infoList = await nowPageList(ctx, ctx.request.body.page);
          let length = await nowLength(ctx);
          ctx.body = {code: "200", msg: "用户信息修改成功", infoList, length}
        }
      }
    }
    if(result.findIndex(item => item.user_id == data.user_id) == '-1') {
      let res = await ctx.db.EXCUTE(insertSql, [produceId(), data.user_name, "123456", data.user_phone, data.user_email, data.user_address, Date.now(), '']);
      console.log(res);
      let Object = ctx.request.body;
      Object.changeTime = Date.now();
      Object.id = produceId();
      Object.password = "123456"
      console.log(Object.id);
      obj.unshift(Object);
      console.log(ctx.request.body);
      let infoList = await nowPageList(ctx, ctx.request.body.page);
      let length = await nowLength(ctx);
      // writeUserFile();
      ctx.body = {code: "200", msg: "添加成功", infoList, length};
    }
  } else {
      ctx.body = {code: "500", msg: "请先登录"}
  }
});

// 已修改
router.post("/page", async (ctx, next) => {
  let infoList = await nowPageList(ctx, ctx.request.body.page);
  let length = await nowLength(ctx);
  ctx.body = {code: 200, msg: "成功获取信息" , infoList, length};
})

// 已修改
router.post("/register", async (ctx, next) => {
  let data = ctx.request.body;
  // console.log("dwdsa");
  if(obj.findIndex(item => item.username === data.username) != -1) {
    ctx.body = {code: "500", msg: "用户名已存在"}
  } else {
    let userInfo = {};
    let result = await ctx.db.EXCUTE(insertSql, [produceId(), data.username, data.password, data.phone, data.email, '' , Date.now().toString(),'']);
    console.log(result);
    ctx.body = {code: "200", msg: "注册成功"}
  }
})

// 已修改
router.post("/deleteData", async (ctx, next) => {
  let checkRes = await checkToken.cheakToken(ctx);
  if(checkRes) {
    let sql = "delete from users where user_id = ?"
    let result = await ctx.db.EXCUTE(sql, [ctx.request.body.user_id])
    console.log(result);
    console.log(ctx.request.body);
    let infoList = await nowPageList(ctx, ctx.request.body.page);
    let length = await nowLength(ctx);
    ctx.body = {code: "200", msg: "成功删除", infoList, length}
  } else {
      ctx.body = {code: "500", msg: "请先登录"}
  }
});

router.post("/search", async (ctx, next) => {
  let checkRes = await checkToken.cheakToken(ctx);
  if(checkRes) {
    let searchArr = [];
    let mz = '%' + ctx.request.body.content + '%';
    let sql = "select * from users where user_name like ?";
    let result = await ctx.db.EXCUTE(sql, [mz]);

    ctx.body = {code: "200", msg: "搜索成功", infoList: result.slice(0, 10), length: result.length}
  } else {
      ctx.body = {code: "500", msg: "请先登录"}
  }
});

module.exports = router
